package com.huiyeji.dynamic.core.bean;

import com.huiyeji.dynamic.core.DynamicContext;
import com.huiyeji.dynamic.core.DynamicStatement;
import com.huiyeji.dynamic.core.DynamicStatementPointer;
import com.huiyeji.dynamic.core.annotations.DynamicBean;

import java.util.List;

/**
 * @author Huiyeji
 */
@DynamicBean("loop")
public class DynamicLoop {

    private final DynamicStatementPointer pointer;

    private final String loopName;

    private int startIndex;

    private int endIndex;

    public DynamicLoop(DynamicContext context){
        pointer = context.getPointer();
        List<DynamicStatement> statements = pointer.getStatements();
        DynamicStatement curStatement = statements.get(pointer.getCurrentPosition());
        loopName = curStatement.getDynamicResultName();
        if (loopName == null || "".equals(loopName)){
            throw new RuntimeException("Dynamic Loop Result Name Not Found");
        }
        for (int i = pointer.getCurrentPosition() + 1; i < statements.size(); i++) {
            DynamicStatement statement = statements.get(i);
            if (loopName.equals(statement.getDynamicObjectName())){
                if ("start".equals(statement.getDynamicMethodName())){
                    startIndex = i;
                } else if ("end".equals(statement.getDynamicMethodName())) {
                    endIndex = i;
                    break;
                }
            }
        }

        if (startIndex == 0 || startIndex >= endIndex){
            throw new RuntimeException("Dynamic Loop Internal Sort Error");
        }
    }

    public void start(){

    }

    public void end(){
        pointer.setNextPosition(startIndex + 1);
    }
}
